import { Component, OnInit } from '@angular/core';
import { DValidateRules, FormLayout, ToastService } from "ng-devui";
import { UserAuthService } from "src/app/@core/user-auth.service";
import { AuthGuardService } from '../../@core/auth-guard-service.guard';
import { Router, ActivatedRoute } from '@angular/router'

@Component({
  selector: 'app-phone-connect',
  templateUrl: './phone-connect.component.html',
  styleUrls: ['./phone-connect.component.scss']
})
export class PhoneConnectComponent implements OnInit {
  layoutDirection: FormLayout = FormLayout.Vertical;
  userId = parseInt(localStorage.getItem('userId'))

  constructor(
    private userAuthService: UserAuthService,
    private authGuardService: AuthGuardService,
    private router: Router,
    private toastService: ToastService,
    private activatedRouter: ActivatedRoute
  ) { }

  countDown = false;
  starttime: any;
  title: string

  ngOnInit(): void {
    this.activatedRouter.queryParams.subscribe(queryParams => {
      this.title = queryParams['type'] === true ? '更换手机' : '绑定手机'
    })
    this.starttime = parseInt(localStorage.getItem("getTelCodeTimeConnect"))
    this.countDown = this.starttime > new Date().getTime()
  }

  options = ["+86"];

  formData = {
    telephoneNumber: "",
    verificationCode: "",
  }

  formRules: { [key: string]: DValidateRules } = {
    rule: {
      messageShowType: "text",
      message: "校验失败，请检查表单信息",
    },

    phoneNumRules: {
      validators: [
        { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: "请输入规范的手机号" },
        { required: true, message: "手机号不能为空" },
      ],
    },

    codeRules: {
      validators: [{ required: true, message: "验证码不能为空" }],
    },
  }

  submitForm({ valid }) {
    if (valid) {
      this.userAuthService.teleConnect(
        this.userId,
        this.formData.telephoneNumber,
        this.formData.verificationCode).subscribe((res) => {
          if (res.code == 0) {
            localStorage.removeItem('getTelCodeTimeConnect')
            this.router.navigate(['/baseUserInfo'])
            this.toastService.open({
              value: [{ severity: 'success', summary: '', content: res.msg }]
            })
          }
          else {
            this.toastService.open({
              value: [{ severity: 'fail', summary: '', content: res.msg }]
            })
          }
        })
    }
  }

  callGetList() {
    this.countDown = false;
  }

  getCode() {
    this.userAuthService.getPhoneCaptcha(this.formData.telephoneNumber, true).subscribe((res) => {
      if (res.code != 0) {
        this.authGuardService.showModalPanel('warning', res.msg)
      }
      else {
        localStorage.setItem("getTelCodeTimeConnect", res.data.cooldownTime)
        if (res.data.cooldownTime > new Date().getTime()) {
          this.countDown = true;
          this.starttime = parseInt(localStorage.getItem("getTelCodeTimeConnect"))
        }
        else {
          this.countDown = false;
        }
      }
    })
  }
}
